package com.backend.demo.util;

import java.lang.reflect.Constructor;

public class ConstructorCaster<T> implements Caster<T> {
	private Class<T> clazz;

	public ConstructorCaster(Class<T> clazz) {
		this.clazz = clazz;
	}

	public T cast(Object o) {
		try {
			if (o == null) {
				return null;
			}
			boolean hav_object=false;
			
			if (o instanceof Object[]) {
				Object[] os = (Object[]) o;				
				Constructor[] cons = clazz.getDeclaredConstructors();
				for (Constructor<T> c : cons) {
					if (os.length == c.getParameterTypes().length) {
						if(c.getParameterTypes()[0].getName().equals("java.lang.Object")){
							hav_object =true;
							break;
						}
					}
				}
				
				for (Constructor<T> c : cons) {
					if (os.length == c.getParameterTypes().length) {						
						if(hav_object){
							if(c.getParameterTypes()[0].getName().equals("java.lang.Object")){
								return c.newInstance(os);
							}
						}else{
							return c.newInstance(os);
						}
					}
				}
				// 表示只有一个	
			} else {
				Constructor[] cons = clazz.getDeclaredConstructors();
				for (Constructor<T> c : cons) {
					if (1 == c.getParameterTypes().length) {
						if(c.getParameterTypes()[0].getName().equals("java.lang.Object")){
							hav_object =true;
							break;
						}
					}
				}
				for (Constructor<T> c : cons) {
					if (1 == c.getParameterTypes().length) {
						if(hav_object){
							if(c.getParameterTypes()[0].getName().equals("java.lang.Object")){
								return c.newInstance(o);
							}
						}else{
							return c.newInstance(o);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return null;
	}

}
